package SparkExercises.kejian4;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class LianXi {
    public static void main(String[] args) {
        /**
         * 已知一个普通的文本文件words.txt，里面每一行都是英文语句，请写一个spark程序，
         * 用reduceByKey统计每个单词的出现次数（按空格分割，每一个子字符串看成一个单词），
         * 并输出到控制台。【说明：以后工作中，不会强制使用某种算子来实现某个功能的。此练习仅仅是为了让大家掌握reduceByKey的用法】
         */
        SparkConf sparkConf = new SparkConf().setAppName("LianXi").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(sparkConf);

        JavaRDD<String> rdd1 = sc.textFile("./data/words.txt");

        JavaRDD<String> rdd2 = rdd1.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" ")).iterator();
            }
        });
        JavaPairRDD<String, Integer> pairRDD = rdd2.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s, 1);
            }

        });
        JavaPairRDD<String, Integer> newRdd = pairRDD.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer integer, Integer integer2) throws Exception {
                return integer + integer2;
            }
        });
        System.out.println(newRdd.collect());

    }
}
